package net.sppan.blog.utils;

import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by liyongyao on 2017/1/24.
 */
public class ShellExec {
    static Logger log = Logger.getLogger(ShellExec.class);

    /**
     * 头两个命令必须是  "/bin/sh", "-c"
     *
     * @param cmd
     * @return
     */
    public static String runShell(String[] cmd) {
        String result = null;
        try {
            for (String c : cmd) {
                log.error(StringTools.format("cmd:{0}", c));
            }
            Process ps = Runtime.getRuntime().exec(cmd);
            BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
                if (!(line.contains("Completed ") && line.contains(" remaining"))) {
                    log.error(StringTools.format("cmd line:{0}", line));
                }
            }
            result = sb.toString();
            log.error("shell exec result:"+result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
